/**
 * author:Administrator
 * date:2016/4/12
 * desc: 下载一个 html、or 文件
 */
'use strict';

// lib
const request = require('request');
const fs = require('fs');
const EventEmitter = require('events').EventEmitter;


class CrawlerWorker extends EventEmitter {

  constructor(id, opt) {
    super();
    this.id = id || 1;
    this.opt = opt || {};
    this.status = 'end';
  }

  requestHTML() {
    var self = this;
    request(self.task.url, function (err, res, body) {
      self.status = 'end';
      self.task.error = err;
      self.task.html = body;
      self.emit('finish');
    });
  }

  requestFile() {
    var self = this;

    if (self.task.minSize || self.task.maxSize) {
      request({url: self.task.url, method: 'HEAD'}, function (err, res, body) {
        if (err) {
          self.status = 'end';
          self.task.error = err;
          self.emit('finish');
          return;
        }
        var needDown = true;
        var len = res.headers["content-length"];
        if (!len) needDown = false;
        needDown = needDown && (!self.task.minSize || len >= self.task.minSize);
        needDown = needDown && (!self.task.maxSize || len <= self.task.maxSize);
        // console.log('len=%s, min=%s, max=%s, needDown=%s', len, self.task.minSize, self.task.maxSize, needDown);
        if (needDown) downFile();
        else {
          console.log('file size %s ,exceed limit, abort', len);
          self.status = 'end';
          self.emit('finish');
        }
      });
    } else {
      downFile();
    }

    function downFile() {
      var file = fs.createWriteStream(self.task.filePath);
      request(self.task.url).pipe(file)
        .on('error', function (err) {
          self.status = 'end';
          self.task.error = err;
          self.emit('finish');
        });

      file.on('finish', function () {
        file.close(function () {
          self.status = 'end';
          console.log('down success:', self.task.url);
          self.emit('finish');
        });
      });
      file.on('error', function (err) {
        self.status = 'end';
        self.task.error = err;
        self.emit('finish');
      });
    }
  }

  getTask() {
    return this.task;
  }

  /**
   * @param task
   * @param task.url
   * @param task.filePath   optional 如果存在，则下载为文件
   * @param task.minSize    optional filePath存在时有意义
   * @param task.maxSize    optional filePath存在时有意义
   */
  start(task) {
    if (this.opt.debug)
      console.log('worker:' + this.id, task.url);

    if (this.status != 'end') {
      console.error('worker already start');
      return;
      // throw new Error('worker is busy');
    }

    this.task = task;
    this.status = 'start';

    if (task.filePath) this.requestFile();
    else this.requestHTML();
  }
}

module.exports = CrawlerWorker;

// let worker = new CrawlerWorker();
// worker.on('finish', function () {
//   if (worker.error) return console.log(worker.error);
//   let task = worker.getTask();
//   if (task.filePath) console.log(task.filePath);
//   else console.log(task.html);
// });
// worker.start({
//   url: 'https://www.google.com.hk/images/nav_logo242.png',
//   filePath: './foo.jpg'
// });
// worker.start({url: 'http://www.baidu.com'});